package com.open.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.open.annotation.Limit;
import com.open.annotation.RepeatSubmit;
import com.open.bean.AiDrawServer;
import com.open.bean.IpWhite;
import com.open.bean.PaintingRecord;
import com.open.bean.vo.OpenVo;
import com.open.component.JwtComponent;
import com.open.result.OpenResult;
import com.open.server.ImgAIServer;
import com.open.service.AiDrawServerService;
import com.open.service.IpWhiteService;
import com.open.service.PaintingRecordService;
import com.open.util.SystemQueryUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@RestController
@RequestMapping("/request/open")
@Slf4j
public class AIImgController {

    @Autowired
    ImgAIServer imgAIServer;

    @Autowired
    PaintingRecordService paintingRecordService;

    @Autowired
    JwtComponent jwtComponent;

    @Autowired
    IpWhiteService ipWhiteService;

    @Autowired
    AiDrawServerService aiDrawServerService;

    @PostMapping("/n1/get/img")
    @Limit
    @RepeatSubmit
    public OpenResult getImg(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        String wId = jwtComponent.getUserWId(request);
        IpWhite ipWhite = ipWhiteService.getById(wId);

        log.info("当前入参=========={}",jsonObject);

        if (StrUtil.isBlank(jsonObject.getStr("prompt"))){
            return OpenResult.error("写输入图片描述 “prompt” ");
        }
        if (jsonObject.getInt("sid") == null || jsonObject.getInt("serverType") == null){
            return OpenResult.error("请选择要绘画的服务器");
        }

        if (ipWhite.getRequestCount() < 3){
            return OpenResult.error("你的余额已经用完！如果想继续绘画，请加群聊：237343691，联系群主");
        }

        if (aiDrawServerService.getById(jsonObject.getInt("sid")).getServerStatus() == 1) {
            return OpenResult.error("当前服务器被禁用！");
        }

        OpenVo serverImg = new OpenVo();
        if(SystemQueryUtil.isWindows()){
            serverImg.setState(true);
            serverImg.setMsg("成功");
            serverImg.setData("https://baai-flagstudio.ks3-cn-beijing.ksyuncs.com/web/e27636316af44b10ac3423406bc322bd/generated/20221231201609-4432154ebbbd4432850a20b5ecb5a9e7/0@base@tag=imgScale");
        }else {
            serverImg  = imgAIServer.getImg(jsonObject,wId,ipWhiteService);
        }


        if (serverImg.isState()) {
            jsonObject.set("upsample",1);
            PaintingRecord paintingRecord = new PaintingRecord();
            paintingRecord.setSid(jsonObject.getInt("sid"));
            paintingRecord.setServerType(jsonObject.getInt("serverType"));
            paintingRecord.setImgBase(serverImg.getData());
            paintingRecord.setUserType(ipWhite.getUserType());
            paintingRecord.setUserHeadImg(StrUtil.isBlank(ipWhite.getHeadImg())?"":ipWhite.getHeadImg());
            paintingRecord.setUserNickname(ipWhite.getNikeName());
            paintingRecord.setUserUsername(ipWhite.getEmail());
            paintingRecord.setCreateTime(new Date());
            paintingRecord.setPrompt(jsonObject.getStr("prompt"));
            paintingRecord.setNegativePrompts(jsonObject.getStr("negative_prompts"));
            paintingRecord.setParticulars(jsonObject.getInt("steps"));
            paintingRecord.setGuidanceScale(jsonObject.getDouble("guidance_scale"));
            paintingRecord.setImgBi(jsonObject.getStr("aiDrawWidthHeight"));
            paintingRecord.setSampler(jsonObject.getStr("sampler"));
            if (StrUtil.isBlank(jsonObject.getStr("seed"))){
                Random random = new Random();
                long seed = random.nextLong() & 0xfffffffffffffffL;
                jsonObject.set("seed",seed);
            }
            paintingRecord.setSeed(jsonObject.getStr("seed"));
            paintingRecord.setSteps(jsonObject.getInt("steps"));
            paintingRecord.setStyle(jsonObject.getStr("style"));
            paintingRecord.setWid(Integer.parseInt(wId));
            paintingRecordService.save(paintingRecord);
            if (jsonObject.getInt("serverType") == 0){
                List<Integer> serverCount = paintingRecordService.getServerCount(jsonObject.getInt("sid"));
                aiDrawServerService.lambdaUpdate()
                        .set(AiDrawServer::getServerCount,serverCount.size())
                        .eq(AiDrawServer::getSid,jsonObject.getInt("sid"))
                        .update();
            }
            return OpenResult.success(serverImg.getData());
        }else {
            return OpenResult.error(serverImg.getMsg());
        }
    }


}
